import { saveTemplate, getTemplateById, deleteTemplate } from  "../../api/template"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    moveInfo: [] as TemplateTemp[],
    title:"" as string,
    description:"" as string,
    type: "" as string,
    templateId:null as number | null,
    showLoading:true as boolean,
    timer: null as number | null,
    backTimer: null as number | null
  },
  // 跳转到选择部位页面
  toChooseArea(): void {
    // 跳转之前，将删除的信息更新
    const app = getApp<IAppOption>();
    app.globalData.templateTempData = this.data.moveInfo
    wx.navigateTo({
      url: "/pages/chooseArea/chooseArea"
    })
  },
  // 点击删除item
  deleteItem(e: any): void {
    const areaId = e.currentTarget.dataset.id
    const moveItem = e.currentTarget.dataset.item
    this.data.moveInfo.map((item: TemplateTemp) => {
       if(item.areaId === areaId) {
        item.moveInfo = item.moveInfo.filter((move:CardItem) => {
          return move.id !== moveItem.id;
        })
      }
    })
    this.data.moveInfo = this.data.moveInfo.filter(item => item.moveInfo.length > 0);
    this.setData({
      moveInfo: this.data.moveInfo
    })
  },
  // 点击添加模板
  async addTemplate():Promise<void> {
    const app = getApp<IAppOption>()
    if(!this.data.title) {
      wx.showToast({
        title:"标题不能为空",
        icon:'error'
      })
      return
    }
    if(!this.data.moveInfo.length) {
      wx.showToast({
        title:"请选择动作",
        icon:'error'
      })
      return
    }
    // 数据处理
    
    const params = {
      templateId: this.data.templateId,
      areaInfo:  this.data.moveInfo,
      title: this.data.title,
      description: this.data.description
    }
    // 掉接口保存模板
    const result = await saveTemplate(params);
    if(!result.code) {
      // 清数据
      app.globalData.templateTempData = []
      wx.showToast({
        title: this.data.type == "edit"?"修改成功":"添加成功",
        icon: "success"
      })
      this.data.backTimer = setTimeout(() => {
        wx.navigateBack();
      }, 1000)
    }
  },
  // 输入框内容改变
  handleInput(e:any): void {
    if (e.currentTarget.dataset.type === "title") {
      this.setData({
        title: e.detail.value
      })
    }else {
      this.setData({
        description: e.detail.value
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      type: options.type,
      showLoading: options.type=='add'?false:true
    })
    const channel = this.getOpenerEventChannel();
    channel.on("templateInfo" , async ({info}:{info:Template}) => {
      this.setData({
        title: info.title,
        description: info.description,
        templateId: info.id
      })
      // 根据ID获取模板信息
      await this.getTemplateById(info.id as number)
      this.data.timer = setTimeout(() => {
        this.setData({
          showLoading: false
        })
      })
    })
  },
  // 根据ID获取模板信息
  async getTemplateById(id:number): Promise<void> {
    const result:Response = await getTemplateById(id);
    if(result.code == 0) {
      this.setData({
        moveInfo: result.data
      })
    }
  },

  // 修改状态
  changeStatus(): void {
    this.setData({
      type:"edit"
    })
  },
  cancelEdit(): void {
    this.setData({
      type: "view"
    })
  },
  delete(): void {
    wx.showModal({
      title:"删除模板",
      content:"确认是否删除该模板",
      success: async (res) => {
        if(res.confirm) {
          await deleteTemplate(this.data.templateId as number)
          wx.showToast({
            title:"删除成功",
            icon:"success"
          })
          this.data.backTimer = setTimeout(() => {
            wx.navigateBack();
          }, 1000)
        }
      }
    })
  },
  // 去修改信息
  editMove(e:any): void {
    // 在查看模式下，才能添加动作
    if(this.data.type == "view") {
      // 获取点击信息
      const areaInfo: TemplateTemp = e.currentTarget.dataset.areainfo
      const index: number = e.currentTarget.dataset.index
      // 获取年月日信息
      const now = new Date(); // 获取当前时间
      const year = now.getFullYear(); // 获取当前年份
      const month = now.getMonth() + 1; // 获取当前月份（注意：JavaScript 中 getMonth() 返回的是 0-11，需要加1才是实际的1-12月）
      const day = now.getDate(); // 获取当前日
      wx.navigateTo({
        url:"/pages/editExist/editExist",
        success: (res) => {
          res.eventChannel.emit("getDetailList" , {
            date: {
              year,
              month: month.toString().padStart(2,"0"),
              today: day.toString().padStart(2,'0')
            },
            data: {
              exerciseAreaId: areaInfo.areaId,
              exerciseMoveId: areaInfo.moveInfo[index].id,
              exerciseName: areaInfo.moveInfo[index].name,
              group: 0,
              per:null,
              unit:"kg",
              weight:null
            },
            type:"add"
          })
        }
      })
    }
    console.log(e)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const app = getApp<IAppOption>();
    // 如果是view，app.globalData.templateTempData中没数据。就会导致空
    if(this.data.type != "view") {
      this.setData({
        moveInfo: app.globalData.templateTempData
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {      
    const app = getApp<IAppOption>();
    app.globalData.templateTempData = []; 
    this.setData({
      timer: null,
      backTimer: null
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})